package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.burgeon.backend.SHOPBACKEND.entity.*;
import com.burgeon.backend.SHOPBACKEND.mappers.BackendActivityMapper;
import com.burgeon.backend.SHOPBACKEND.mappers.BackendGoodsMapper;
import com.burgeon.backend.SHOPBACKEND.mappers.GoodsBackendClassifyMapper;
import com.burgeon.backend.SHOPBACKEND.rest.*;
import com.burgeon.backend.SHOPBACKEND.service.BackendGoodsService;
import com.burgeon.backend.SHOPBACKEND.service.ex.DeleteException;
import com.burgeon.backend.SHOPBACKEND.service.ex.ErrorDataException;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.ex.UploadException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.Encoder;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;
import ws.schild.jave.info.AudioInfo;
import ws.schild.jave.info.VideoSize;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.burgeon.backend.SHOP.service.Impl.OrderServiceImpl.getOrderIdByUUId;

@Service
public class BackendGoodsServiceImpl implements BackendGoodsService {
    private final static Log logger = LogFactory.getLog(BackendGoodsService.class);

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private BackendGoodsMapper backendGoodsMapper;
    @Autowired
    private GoodsBackendClassifyMapper goodsBackendClassifyMapper;

    //上传商品视频
    @Override
    public String uploadProductVideo(MultipartFile video, String account) throws ErrorDataException {
        String gid = getOrderIdByUUId();

        System.err.println(account+"'"+(null==video?"kong":"you"));
        if (null == video || video.isEmpty()) {
            //删除视频
           // Integer row = backendGoodsMapper.upGoodsVideo(gid, null);

              throw new ErrorDataException("视频文件为空");
            //System.err.println("删除视频");
           // return;
        }
        String fileName = video.getOriginalFilename(); //文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名

        String filePath = "//root//code//img//" + account + "-shop//goods//video//"; // 上传后的路径
        fileName = gid + "-video" + suffixName; // 新文件名

      //  Integer row = backendGoodsMapper.upGoodsVideo(gid, "http://lfwdcdn.cloudsmicro.com/img/" + account + "-shop/goods/video/" + fileName);

//        if (1 != row) {
//            throw new ErrorDataException("商品上传出错");
//        }


        saveFile(video, fileName, filePath);

        return "http://lfwdcdn.cloudsmicro.com/img/" + account + "-shop/goods/video/" + fileName;
    }

    public static void main(String[] args) {
        File file = new File("D://test1.mp4");
        File file1 = compressionVideo(file, "tt.mp4");

        System.err.println(file1.getPath());

    }


    /**
     * 传视频File对象（这是一个具体的文件），返回压缩后File对象信息
     *
     * @param source
     */
    private static File compressionVideo(File source, String picName) {
        if (source == null) {
            return null;
        }
        String newPath = source.getAbsolutePath().substring(0, source.getAbsolutePath().lastIndexOf(File.separator)).concat(File.separator).concat(picName);
        File target = new File(newPath);
        try {
            MultimediaObject object = new MultimediaObject(source);
            AudioInfo audioInfo = object.getInfo().getAudio();
            // 根据视频大小来判断是否需要进行压缩,
            int maxSize = 5;
            double mb = Math.ceil(source.length() / 1048576);
            int second = (int) object.getInfo().getDuration() / 1000;
            BigDecimal bd = new BigDecimal(String.format("%.4f", mb / second));
            System.out.println("开始压缩视频了--> 视频每秒平均 " + bd + " MB ");
            // 视频 > 5MB, 或者每秒 > 0.5 MB 才做压缩， 不需要的话可以把判断去掉
            boolean temp = mb > maxSize || bd.compareTo(new BigDecimal(0.5)) > 0;
            if (temp) {
                long time = System.currentTimeMillis();
                //TODO 视频属性设置
                int maxBitRate = 128000;
                int maxSamplingRate = 44100;
                int bitRate = 800000;
                int maxFrameRate = 20;
                int maxWidth = 1280;

                AudioAttributes audio = new AudioAttributes();
                // 设置通用编码格式10                   audio.setCodec("aac");
                // 设置最大值：比特率越高，清晰度/音质越好
                // 设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 128000 = 182kb)
                if (audioInfo.getBitRate() > maxBitRate) {
                    audio.setBitRate(new Integer(maxBitRate));
                }

                // 设置重新编码的音频流中使用的声道数（1 =单声道，2 = 双声道（立体声））。如果未设置任何声道值，则编码器将选择默认值 0。
                audio.setChannels(audioInfo.getChannels());
                // 采样率越高声音的还原度越好，文件越大
                // 设置音频采样率，单位：赫兹 hz
                // 设置编码时候的音量值，未设置为0,如果256，则音量值不会改变
                // audio.setVolume(256);
                if (audioInfo.getSamplingRate() > maxSamplingRate) {
                    audio.setSamplingRate(maxSamplingRate);
                }

                //TODO 视频编码属性配置
                ws.schild.jave.info.VideoInfo videoInfo = object.getInfo().getVideo();
                VideoAttributes video = new VideoAttributes();
                video.setCodec("h264");
                //设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 800000 = 800kb)
                if (videoInfo.getBitRate() > bitRate) {
                    video.setBitRate(bitRate);
                }

                // 视频帧率：15 f / s  帧率越低，效果越差
                // 设置视频帧率（帧率越低，视频会出现断层，越高让人感觉越连续），视频帧率（Frame rate）是用于测量显示帧数的量度。所谓的测量单位为每秒显示帧数(Frames per Second，简：FPS）或“赫兹”（Hz）。
                if (videoInfo.getFrameRate() > maxFrameRate) {
                    video.setFrameRate(maxFrameRate);
                }

                // 限制视频宽高
                int width = videoInfo.getSize().getWidth();
                int height = videoInfo.getSize().getHeight();
                if (width > maxWidth) {
                    float rat = (float) width / maxWidth;
                    video.setSize(new VideoSize(maxWidth, (int) (height / rat)));
                }

                EncodingAttributes attr = new EncodingAttributes();
//                attr.setFormat("mp4");
                attr.setAudioAttributes(audio);
                attr.setVideoAttributes(video);

                // 速度最快的压缩方式， 压缩速度 从快到慢： ultrafast, superfast, veryfast, faster, fast, medium,  slow, slower, veryslow and placebo.
//                attr.setPreset(PresetUtil.VERYFAST);
//                attr.setCrf(27);
//                // 设置线程数
//                attr.setEncodingThreads(Runtime.getRuntime().availableProcessors()/2);

                Encoder encoder = new Encoder();
                encoder.encode(new MultimediaObject(source), target, attr);
                System.out.println("压缩总耗时：" + (System.currentTimeMillis() - time) / 1000);
                return target;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (target.length() > 0) {
                source.delete();
            }
        }
        return source;
    }


    @Override
    public void upGoodsStateAll(String[] ids) throws ErrorDataException {
        for (String id : ids) {
            try {
                Goods goods = backendGoodsMapper.getGoodsById(id);
                backendGoodsMapper.upGoodsState(id, "Y".equals(goods.getIsPutaway()) ? "N" : "Y");
            } catch (Exception e) {
                e.printStackTrace();
                throw new ErrorDataException("出现错误");
            }
        }
    }

    @Override
    public void cancelPackageMailed(String gids, String account) {
        try {
            String[] gidArr = gids
                    .replace("\"", "")
                    .replace("]", "")
                    .replace("[", "")
                    .replace(" ", "")
                    .trim()
                    .split(",");
            for (String gid : gidArr) {
                backendGoodsMapper.freeShipping(gid, "N");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }
    }

    @Override
    public List<Goods> getExemptionMailList(String account) {
        return backendGoodsMapper.getExemptionMailList(account);

    }

    @Override
    public void freeShipping(String str, String account) throws ErrorDataException {
        try {
            String[] gidArr = str
                    .replace("\"", "")
                    .replace("]", "")
                    .replace("[", "")
                    .replace(" ", "")
                    .trim()
                    .split(",");
            for (String gid : gidArr) {
                backendGoodsMapper.freeShipping(gid, "Y");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());

        }

    }

    @Override
    public void changeAllLabel(String[] gids, String lable) throws ErrorDataException {

        for (String gid : gids) {

            try {
                Integer row = backendGoodsMapper.changeAllLabel(gid, lable);
                System.out.println(row);
                if (1 != row) {
                    throw new ErrorDataException("出现错误");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new ErrorDataException("出现错误");
            }

        }
    }


    @Override
    public HashMap findGoodsDataByClass(String name, String account) {
        HashMap data = new HashMap();
        List<Goods> goods = backendGoodsMapper.findGoodsDataByClass(name, account);
        for (Goods goodsData : goods) {
            goodsData.setPutaway(goodsData.getIsPutaway().equals("Y"));
            goodsData.setGoodsItems(backendGoodsMapper.GetGoodsItem(goodsData.getId()));
            for (GoodsItem goodsItem : goodsData.getGoodsItems()) {
                goodsItem.setGoodsSizes(backendGoodsMapper.GetGoodsSize(goodsItem.getId()));
            }
        }
        data.put("goods", goods);
        data.put("count", goods.size());
        return data;
    }

    @Override
    public void syncAll(String type, String message, String message1, String account) throws ErrorDataException {
        Info info = GetInfo(account);

        Thread thread = new Thread(() -> {
            try {
                if ("C".equals(type)) {
                    //条件查找同步
                    QueryClassificationBySync queryClassificationBySync = new QueryClassificationBySync(info.getUrl(), info.getAccount(), info.getPassword());
                    if (message == null && message1 == null) {
                        return;
                    }
                    HashMap data = null;
                    try {
                        data = queryClassificationBySync.getData(message, message1);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    //addGoodsCache((ArrayList<Classification>) data.get("goods"), account);
                    //System.err.println((ArrayList<Classification>) data.get("goods"));
                    ArrayList<Classification> classifications = (ArrayList<Classification>) data.get("goods");
                    System.err.println(classifications.size());

                    for (Classification classification : classifications) {
                        //判断款号是否存在
                        if (null != backendGoodsMapper.findGoodsByCode(classification.getName(), account)) {
                            continue;
                            //throw new ErrorDataException("商品:" + data.getValue() + "--" + data.getName() + "已存在");
                        }
                        classification.setAccount(account);
                        backendGoodsMapper.addClassification(classification);
                    }

                } else { //D 款号同步
                    //款号查找同步
                    if (message == null) {
                        return;
                    }
                    HashMap data = findGoodsByCode(message, account);
                    addGoodsCache((ArrayList<Classification>) data.get("goods"), account);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new ErrorDataException("出现错误");
            }
        });
        thread.start();

    }

    @Override
    public Goods findGoodsDataByCode(String code, String account) {
        Goods data = backendGoodsMapper.findGoodsDataByCode(code, account);
        data.setPutaway(data.getIsPutaway().equals("Y"));
        data.setGoodsItems(backendGoodsMapper.GetGoodsItem(data.getId()));
        for (GoodsItem goodsItem : data.getGoodsItems()) {
            goodsItem.setGoodsSizes(backendGoodsMapper.GetGoodsSize(goodsItem.getId()));
        }
        return data;
    }

    @Override
    public List<Classification> getGoodsCacheByUse(String account, String use) {
        return backendGoodsMapper.GetClassificationByUse(account, use);
    }

    @Override
    public HashMap getGoodsById(String id) {

        Goods goods = backendGoodsMapper.getGoodsById(id);
        HashMap data = new HashMap();
        HashMap base = new HashMap();
        base.put("id", goods.getId());
        base.put("type", goods.getType());
        base.put("price", goods.getPrice());
        base.put("code", goods.getCode());
        base.put("name", goods.getName());
        base.put("classify", goods.getClassify());
        base.put("classifyitem", goods.getClassifyItem());
        base.put("isPutaway", goods.getIsPutaway());
        base.put("presentation", goods.getPresentation());
        base.put("integral", goods.getIntegral());
        base.put("original", goods.getOriginal());
        base.put("activity", goods.getActivity());
        base.put("activityID", goods.getActivityID());
        base.put("label", goods.getLabel());
        base.put("isPlusPrice", goods.getIsPlusPrice());
        base.put("isVipPrice", goods.getIsVipPrice());
        base.put("plusPrice", goods.getPlusPrice());
        base.put("video",goods.getVideo());
        data.put("base", base);

        List<GoodsItem> goodsItems = backendGoodsMapper.GetGoodsItem(goods.getId());
        ArrayList item = new ArrayList();
        for (GoodsItem goodsItem : goodsItems) {
            HashMap itemData = new HashMap();
            itemData.put("color", goodsItem.getName());
            itemData.put("show", goodsItem.getIsShow());
            ArrayList size = new ArrayList();
            List<GoodsSize> goodsSizes = backendGoodsMapper.GetGoodsSize(goodsItem.getId());
            for (GoodsSize goodsSize : goodsSizes) {
                HashMap sizeData = new HashMap();
                sizeData.put("key", goodsSize.getName());
                sizeData.put("show", goodsSize.getIsShow());
                sizeData.put("num", goodsSize.getInventory());
                sizeData.put("code", goodsSize.getCode());
                size.add(sizeData);
            }
            itemData.put("size", size);
            item.add(itemData);
        }

        data.put("item", item);
        HashMap img = new HashMap();
        img.put("main", goods.getImg());
        //itemimg
        List<GoodsItemImg> goodsItemImgs = backendGoodsMapper.getGoodsItemImg(goods.getId());
        ArrayList goodsItImg = new ArrayList();
        for (GoodsItemImg goodsItemImg : goodsItemImgs) {
            HashMap itemimgData = new HashMap();
            itemimgData.put("img", goodsItemImg.getImg());
            itemimgData.put("id", goodsItemImg.getId());
            goodsItImg.add(itemimgData);
        }

        img.put("item", goodsItImg);
        List<Banner> banners = backendGoodsMapper.getBanner(goods.getId());
        ArrayList banner = new ArrayList();
        for (Banner goodsBanner : banners) {
            HashMap bannerdata = new HashMap();
            bannerdata.put("img", goodsBanner.getUrl());
            bannerdata.put("id", goodsBanner.getId());
            banner.add(bannerdata);
        }
        img.put("banner", banner);
        img.put("attribute", goods.getAttributeImg());

        data.put("img", img);

        return data;
    }

    @Override
    public List<Classification> getGoodsCache(String account) {
        return backendGoodsMapper.GetClassification(account);
    }

    @Override
    public void addGoodsCache(List<Classification> classification, String account) throws ErrorDataException {
        try {
            for (Classification data : classification) {
                //判断款号是否存在
                if (null != backendGoodsMapper.findGoodsByCode(data.getName(), account)) {
                    break;
                    //throw new ErrorDataException("商品:" + data.getValue() + "--" + data.getName() + "已存在");
                }
                data.setAccount(account);
                backendGoodsMapper.addClassification(data);

            }
        } catch (Exception e) {
            throw new ErrorDataException(e.getMessage());
        }
    }

    @Override
    public HashMap findGoodsByCode(String code, String account) {
        Info info = GetInfo(account);
        QueryGoodsByCode queryGoodsByCode = new QueryGoodsByCode(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            return queryGoodsByCode.getData(code);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void upGoodsState(String id, String state) throws ErrorDataException {
        try {
            backendGoodsMapper.upGoodsState(id, state);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException("出现错误");
        }
    }

    @Override  //删除商品信息
    @Transactional
    public void DeleteGoods(String id, String account) throws DeleteException {

        try {
            Goods goods = backendGoodsMapper.getGoodsById(id);
            backendGoodsMapper.DeGoods(id);//删除商品

            backendGoodsMapper.upGoodsCacheUse(goods.getCode(), account, "N");
            List<GoodsItem> findIdByGid = backendGoodsMapper.findIdByGid(id);

            backendGoodsMapper.DeGI(id);//根据gid删除商品Item

            for (GoodsItem gid : findIdByGid) {
                backendGoodsMapper.DeGoodsSize(gid.getId());//删除GoodsSize
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new DeleteException(e.getMessage());
        }
    }

    @Override
    public HashMap GetGoodsAll(int start, String account) {
        HashMap data = new HashMap();

        List<Goods> goods = backendGoodsMapper.getGoodsAll(start * 50, account);
        String count = backendGoodsMapper.GoodsCount(account);

        for (Goods goodsData : goods) {
            goodsData.setPutaway(goodsData.getIsPutaway().equals("Y"));
            goodsData.setGoodsItems(backendGoodsMapper.GetGoodsItem(goodsData.getId()));
            for (GoodsItem goodsItem : goodsData.getGoodsItems()) {
                goodsItem.setGoodsSizes(backendGoodsMapper.GetGoodsSize(goodsItem.getId()));
            }
        }

        data.put("goods", goods);
        data.put("count", count);

        return data;
    }

    @Override
    public HashMap GetProductalias(String id, String account) {
        System.err.println(id);
        Info info = GetInfo(account);

        GetPRODUCTALIAS getPRODUCTALIAS = new GetPRODUCTALIAS(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getPRODUCTALIAS.getData(id);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    @Override
    @Transactional
    public void UpGoods(String data,
                        MultipartFile[] files,
                        MultipartFile[] itemimg,
                        MultipartFile mfile,
                        MultipartFile attribute,
                        String account, String[] bid, String[] tid) throws ErrorDataException {


        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONObject jsonObject1 = jsonObject.getJSONObject("base");

            //写入主表
            Goods goods = new Goods();

            goods.setVideo(jsonObject1.getString("videoUrl"));

            goods.setId(jsonObject1.getString("id"));
            goods.setType(jsonObject1.getString("type"));
            goods.setName(jsonObject1.getString("name"));

            goods.setPresentation(jsonObject1.getString("presentation"));

            goods.setPrice(jsonObject1.getString("price"));

            goods.setIsVipPrice(jsonObject1.getString("isVipPrice"));
            goods.setIsPlusPrice(jsonObject1.getString("isPlusPrice"));
            goods.setPlusPrice(jsonObject1.getString("plusPrice"));

            goods.setIntegral(jsonObject1.getString("integral"));
            goods.setIsPutaway(jsonObject1.getString("isPutaway"));

            goods.setClassify(jsonObject1.getString("classify"));
            goods.setClassifyItem(jsonObject1.getString("classifyitem"));
            goods.setActivity(jsonObject1.getString("activity"));
            goods.setActivityID(jsonObject1.getString("activityID"));
            goods.setOriginal(jsonObject1.getString("original"));
            goods.setLabel(jsonObject1.getString("label"));
            if (goods.getLabel().trim().length() == 0 && "null".equals(goods.getLabel())) {
                goods.setLabel(null);
            }
            goods.setToken(account);
            goods.setAccount(account);

            for (String id : bid) {
                backendGoodsMapper.delGoodsBanner(id, account);
            }
            for (String id : tid) {
                backendGoodsMapper.delGoodsItemImg(id);
            }

            backendGoodsMapper.updateGoods(goods);

            int c = backendGoodsMapper.getGoodsMaxBannerNumByGid(goods.getId()) != null ? backendGoodsMapper.getGoodsMaxBannerNumByGid(goods.getId()) : 0;
            int d = backendGoodsMapper.getGoodsMaxItemImgNumByGid(goods.getId()) != null ? backendGoodsMapper.getGoodsMaxItemImgNumByGid(goods.getId()) : 0;
            UploadData(files, itemimg, mfile, attribute, account, goods.getId(), c, d);
            JSONArray jsonArray = jsonObject.getJSONArray("item");
            List<GoodsItem> giids = backendGoodsMapper.findIdByGid(jsonObject1.getString("id"));

            backendGoodsMapper.DeGI(jsonObject1.getString("id"));

            for (GoodsItem giid : giids) {
                backendGoodsMapper.DeGoodsSize(giid.getId());
            }
            if (0 == jsonArray.length()) {
                throw new ErrorDataException("选择商品颜色");
            }
            boolean col = false;
            boolean siz = false;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                GoodsItem goodsItem = new GoodsItem();
                goodsItem.setName(jsonObject2.getString("color"));
                goodsItem.setShow(jsonObject2.getString("show"));
                goodsItem.setGid(goods.getId());

                if ("true".equals(jsonObject2.getString("show"))) {
                    col = true;
                }

                backendGoodsMapper.addGoodsColor(goodsItem);
                if (0 == jsonObject2.getJSONArray("size").length()) {
                    throw new ErrorDataException("选择商品尺寸");
                }
                for (int j = 0; j < jsonObject2.getJSONArray("size").length(); j++) {
                    //写入尺寸
                    GoodsItem sgoodsItem = new GoodsItem();
                    sgoodsItem.setName(jsonObject2.getJSONArray("size").getJSONObject(j).getString("key"));
                    sgoodsItem.setInventory(Integer.parseInt(jsonObject2.getJSONArray("size").getJSONObject(j).getString("num")));
                    sgoodsItem.setCode(jsonObject2.getJSONArray("size").getJSONObject(j).getString("code"));
                    sgoodsItem.setShow(jsonObject2.getJSONArray("size").getJSONObject(j).getString("show"));
                    sgoodsItem.setGiid(goodsItem.getId());
                    if ("true".equals(jsonObject2.getJSONArray("size").getJSONObject(j).getString("show"))) {
                        siz = true;
                    }
                    backendGoodsMapper.addGoodsSize(sgoodsItem);
                }
            }
            if (!col) {
                throw new ErrorDataException("至少有一款颜色");
            }
            if (!siz) {
                throw new ErrorDataException("至少有一款尺码");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }
    }

    @Override
    public ArrayList<Dimdef> GetDimdef(String account) {
        Info info = GetInfo(account);

        GetDIMDEF getDIMDEF = new GetDIMDEF(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getDIMDEF.getData();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public ArrayList<Dimdef> GetSmallDimdef(String id, String account) {
        Info info = GetInfo(account);
        GetSamallDIMDEF getSamallDIMDEF = new GetSamallDIMDEF(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getSamallDIMDEF.getData(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 新增同步商品
     *
     * @throws ErrorDataException
     */
    @Override
    @Transactional
    public String addGoods(String data,
                         MultipartFile[] files,
                         MultipartFile[] itemimg,
                         MultipartFile mfile,
                         MultipartFile attribute,
                         String account) throws ErrorDataException {
        System.err.println("files=" + files.length);
        System.err.println("itemimg=" + itemimg.length);

        if (files.length == 0 || itemimg.length == 0 || mfile == null) {
            throw new ErrorDataException("图片不能为空");
        }

        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONObject jsonObject1 = jsonObject.getJSONObject("base");

            //写入主表
            Goods goods = new Goods();
            goods.setVideo(jsonObject1.getString("videoUrl"));
            goods.setType(jsonObject1.getString("type"));
            goods.setName(jsonObject1.getString("name"));
            goods.setCode(jsonObject1.getString("code"));
            if (null != backendGoodsMapper.getGoodsIdByCode(goods.getCode(), account)) {
                throw new ErrorDataException("商品已存在");
            }
            goods.setPresentation(jsonObject1.getString("presentation"));

            goods.setPrice(jsonObject1.getString("price"));

            goods.setIsVipPrice(jsonObject1.getString("isVipPrice"));
            goods.setIsPlusPrice(jsonObject1.getString("isPlusPrice"));
            goods.setPlusPrice(jsonObject1.getString("plusPrice"));

            goods.setIntegral(jsonObject1.getString("integral"));
            goods.setIsPutaway(jsonObject1.getString("isPutaway"));

            goods.setClassify(jsonObject1.getString("classify"));
            goods.setClassifyItem(jsonObject1.getString("classifyitem"));
            goods.setActivity(jsonObject1.getString("activity"));
            goods.setActivityID(jsonObject1.getString("activityID"));
            goods.setOriginal(jsonObject1.getString("original"));
            goods.setLabel(jsonObject1.getString("label"));
            if (goods.getLabel().trim().length() == 0 && "null".equals(goods.getLabel())) {
                goods.setLabel(null);
            }
            goods.setBrand(getBrand(jsonObject1.getString("brand"), account));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
            String dateString = sdf.format(new Date());
            goods.setCreateDate(dateString);
            goods.setToken(account);
            goods.setAccount(account);
            backendGoodsMapper.addGoods(goods);
            addUploadData(files, itemimg, mfile, attribute, account, goods.getId());
            JSONArray jsonArray = jsonObject.getJSONArray("item");
            if (0 == jsonArray.length()) {
                throw new ErrorDataException("选择商品颜色");
            }
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                //写入明细

                GoodsItem goodsItem = new GoodsItem();
                goodsItem.setName(jsonObject2.getString("color"));
                goodsItem.setShow(jsonObject2.getString("show"));
                goodsItem.setGid(goods.getId());
                backendGoodsMapper.addGoodsColor(goodsItem);
                if (0 == jsonObject2.getJSONArray("size").length()) {
                    throw new ErrorDataException("选择商品尺寸");
                }
                for (int j = 0; j < jsonObject2.getJSONArray("size").length(); j++) {
                    //写入尺寸
                    GoodsItem sgoodsItem = new GoodsItem();
                    sgoodsItem.setName(jsonObject2.getJSONArray("size").getJSONObject(j).getString("key"));
                    sgoodsItem.setInventory(Integer.parseInt(jsonObject2.getJSONArray("size").getJSONObject(j).getString("num")));
                    sgoodsItem.setGiid(goodsItem.getId());
                    sgoodsItem.setCode(jsonObject2.getJSONArray("size").getJSONObject(j).getString("code"));
                    sgoodsItem.setShow(jsonObject2.getJSONArray("size").getJSONObject(j).getString("show"));

                    backendGoodsMapper.addGoodsSize(sgoodsItem);
                }
            }
            //更改商品缓存表状态
            backendGoodsMapper.upGoodsCacheUse(goods.getCode(), account, "Y");
            return goods.getId();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }



    }

    @Override
    public HashMap QueryClassification(Integer start, String id, String value, String account) {

        Info info = GetInfo(account);
        QueryClassification queryClassification = new QueryClassification(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return queryClassification.getData(start, id, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //批量修改商品销售区域
    @Override
    public void changeAllType(String[] gids, String type) {
        for (String gid : gids) {
            try {
                Integer row = backendGoodsMapper.changeAllType(gid, type);
                if (1 != row) {
                    throw new UploadException("出现错误");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new UploadException("出现错误");
            }
        }
        ;
    }

    //批量修改商品活动方案
    @Override
    public void changeAllActivity(String[] gids, String activityID, String activity) {
        try {
            for (String gid : gids) {
                Integer row = backendGoodsMapper.changeAllActity(gid, activityID, activity);
                System.err.println(row);
                if (1 != row) {
                    throw new UploadException("出现错误");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new UploadException("出现错误");
        }
    }

    /**
     * 获取品牌id 如没有此品牌会新建
     *
     * @param data
     * @return
     */
    private String getBrand(String data, String token) {
        Brand brand = goodsBackendClassifyMapper.getBrand(data, token);

        if (null == brand) {
            brand = new Brand();
            brand.setName(data);
            brand.setToken(token);
            int brandMaxNub = goodsBackendClassifyMapper.getBrandMaxNub(token);
            brand.setNub(brandMaxNub + 1);
            goodsBackendClassifyMapper.createBrand(brand);

        }
        return brand.getId();
    }

    private Info GetInfo(String token) {
        return accountMapper.GetAccData(token);
    }

    /**
     * 更新商品图片
     *
     * @param account
     * @param id
     * @throws UploadException
     */
    @Override
    @Transactional
    public void UploadData(MultipartFile[] files, MultipartFile[] itemfile,
                           MultipartFile mfile, MultipartFile attribute,
                           String account, String id, int c, int d) throws UploadException {
        if (mfile.isEmpty()) {
            System.out.println("文件为空");
            throw new UploadException("图片为空");
        }

        for (MultipartFile multipartFile : files) {
            String bfileName = multipartFile.getOriginalFilename(); //文件名
            String bsuffixName = bfileName.substring(bfileName.lastIndexOf("."));// 后缀名

            String bfilePath = "//root//code//img//" + account + "-shop//goods//banner//"; // 上传后的路径

            bfileName = id + "-" + ++c + bsuffixName; // 新文件名

            //存入数据库
            GoodsBanner goodsBanner = new GoodsBanner();
            goodsBanner.setToken(account);
            goodsBanner.setGid(id);
            goodsBanner.setNum(c);
            goodsBanner.setImg(
                    "http://lfwdcdn.cloudsmicro.com/img/" + account +
                            "-shop/goods/banner/" + id + "-" + c + bsuffixName);
            backendGoodsMapper.addGoodsBanner(goodsBanner);

            File bdest = new File(bfilePath + bfileName);
            if (!bdest.getParentFile().exists()) {
                bdest.getParentFile().mkdirs();
            }
            try {
                multipartFile.transferTo(bdest);
            } catch (IOException e) {
                e.printStackTrace();
                throw new UploadException("系统错误");
            } catch (Exception e) {
                System.err.println(e.getMessage());
                throw new UploadException("系统错误");
            }
        }
        for (MultipartFile multipartFile : itemfile) {
            String fileName = multipartFile.getOriginalFilename(); // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名

            String filePath = "//root//code//img//" + account + "-shop//goods//item//"; // 上传后的路径

            fileName = id + "-" + ++d + suffixName; // 新文件名

            //存入数据库
            GoodsItemImg goodsItemImg = new GoodsItemImg();
            goodsItemImg.setGid(id);
            goodsItemImg.setAccount(account);
            goodsItemImg.setToken(account);
            goodsItemImg.setNum(d);

            goodsItemImg.setImg("http://lfwdcdn.cloudsmicro.com/img/" + account + "-shop/goods/item/" + id + "-" + d + suffixName);
            backendGoodsMapper.addGoodsItemImg(goodsItemImg);

            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            try {
                multipartFile.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
                throw new UploadException("系统错误");
            } catch (Exception e) {
                System.err.println(e.getMessage());
                throw new UploadException("系统错误");
            }
        }

        String mfileName = mfile.getOriginalFilename(); //文件名
        String msuffixName = mfileName.substring(mfileName.lastIndexOf("."));// 后缀名

        String attributeFileName;
        String attributeSuffixName = null;
        String attributeImg = null;
        if (null != attribute && !attribute.isEmpty()) {
            attributeFileName = attribute.getOriginalFilename();
            attributeSuffixName = attributeFileName.substring(attributeFileName.lastIndexOf("."));// 后缀名
            attributeImg = "http://lfwdcdn.cloudsmicro.com/img/" + account + "-shop/goods/attribute/" + id + attributeSuffixName;
        }


        String filePath = "//root//code//img//" + account + "-shop//goods//item//"; // 上传后的路径
        String mfilePath = "//root//code//img//" + account + "-shop//goods//";
        String attributePath = "//root//code//img//" + account + "-shop//goods//attribute//";
        //数据库
        backendGoodsMapper.upGoodsImg(id,
                "http://lfwdcdn.cloudsmicro.com/img/" + account + "-shop/goods/" + id + msuffixName,

                attributeImg

        );
        //fileName = id + suffixName; // 新文件名
        mfileName = id + msuffixName;
        attributeFileName = id + attributeSuffixName;
        //File dest = new File(filePath + fileName);
        File mdest = new File(mfilePath + mfileName);


        if (!mdest.getParentFile().exists()) {
            mdest.getParentFile().mkdirs();
        }

        if (null != attribute && !attribute.isEmpty()) {
            File arrtDest = new File(attributePath + attributeFileName);

            if (!arrtDest.getParentFile().exists()) {
                arrtDest.getParentFile().mkdirs();

            }
            try {
                attribute.transferTo(arrtDest);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        try {
            // file.transferTo(dest);
            mfile.transferTo(mdest);


            /*Thumbnails.of(mfilePath + mfileName)
                    .size(335, 390)
                    .keepAspectRatio(false)
                    .toFile(mfilePath + mfileName);*/
        } catch (IOException e) {
            e.printStackTrace();
            throw new UploadException("系统错误");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
            throw new UploadException("系统错误");
        }
    }

    @Transactional
    public void addUploadData(MultipartFile[] files, MultipartFile[] itemfile,
                              MultipartFile mfile, MultipartFile attribute,
                              String account, String id) throws UploadException {
        int c = 0;
        if (files.length == 0 || mfile.isEmpty()) {
            System.out.println("文件为空");
            throw new UploadException("图片为空");
        }

        for (MultipartFile multipartFile : files) {
            String fileName = multipartFile.getOriginalFilename(); // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
            String filePath = "//root//code//img//" + account + "-shop//goods//banner//"; // 上传后的路径

            fileName = id + "-" + ++c + suffixName; // 新文件名

            //存入数据库
            GoodsBanner goodsBanner = new GoodsBanner();
            goodsBanner.setToken(account);
            goodsBanner.setNum(c);
            goodsBanner.setGid(id);
            goodsBanner.setImg("http://lfwdcdn.cloudsmicro.com/img/" + account + "-shop/goods/banner/" + id + "-" + c + suffixName);
            backendGoodsMapper.addGoodsBanner(goodsBanner);

            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            try {
                multipartFile.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
                throw new UploadException("系统错误");
            } catch (Exception e) {
                System.err.println(e.getMessage());
                throw new UploadException("系统错误");
            }
        }
        int d = 0;
        for (MultipartFile multipartFile : itemfile) {
            String fileName = multipartFile.getOriginalFilename(); // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名

            String filePath = "//root//code//img//" + account + "-shop//goods//item//"; // 上传后的路径

            fileName = id + "-" + ++d + suffixName; // 新文件名

            //存入数据库
            GoodsItemImg goodsItemImg = new GoodsItemImg();
            goodsItemImg.setGid(id);
            goodsItemImg.setAccount(account);
            goodsItemImg.setToken(account);
            goodsItemImg.setNum(d);

            goodsItemImg.setImg("http://lfwdcdn.cloudsmicro.com/img/" + account + "-shop/goods/item/" + id + "-" + d + suffixName);
            backendGoodsMapper.addGoodsItemImg(goodsItemImg);

            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            try {
                multipartFile.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
                throw new UploadException("系统错误");
            } catch (Exception e) {
                System.err.println(e.getMessage());
                throw new UploadException("系统错误");
            }
        }


        String mfileName = mfile.getOriginalFilename(); //文件名
        String msuffixName = mfileName.substring(mfileName.lastIndexOf("."));// 后缀名

        String attributeFileName;
        String attributeSuffixName = null;
        String attributeImg = null;
        if (null != attribute && !attribute.isEmpty()) {
            attributeFileName = attribute.getOriginalFilename();
            attributeSuffixName = attributeFileName.substring(attributeFileName.lastIndexOf("."));// 后缀名
            attributeImg = "http://lfwdcdn.cloudsmicro.com/img/" + account + "-shop/goods/attribute/" + id + attributeSuffixName;
        }


        String mfilePath = "//root//code//img//" + account + "-shop//goods//";
        String attributePath = "//root//code//img//" + account + "-shop//goods//attribute//";
        //数据库
        backendGoodsMapper.upGoodsImg(id,
                "http://lfwdcdn.cloudsmicro.com/img/" + account + "-shop/goods/" + id + msuffixName,
                attributeImg
        );

        mfileName = id + msuffixName;
        attributeFileName = id + attributeSuffixName;

        File mdest = new File(mfilePath + mfileName);

        if (null != attribute && !attribute.isEmpty()) {
            File arrtDest = new File(attributePath + attributeFileName);

            if (!arrtDest.getParentFile().exists()) {
                arrtDest.getParentFile().mkdirs();

            }
            try {
                attribute.transferTo(arrtDest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (!mdest.getParentFile().exists()) {
            mdest.getParentFile().mkdirs();
        }

        try {
            //file.transferTo(dest);
            mfile.transferTo(mdest);

            /*Thumbnails.of(mfilePath + mfileName)
                    .size(335, 390)
                    .keepAspectRatio(false)
                    .toFile(mfilePath + mfileName);*/
        } catch (IOException e) {
            e.printStackTrace();
            throw new UploadException("系统错误");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
            throw new UploadException("系统错误");
        }

    }

    //保存文件
    private void saveFile(MultipartFile multipartFile, String fileName, String filePath) {
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        }
    }

}
